package com.wlb.es.util;

import com.wlb.es.entity.User;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class EsUtil {

    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;

    public void createIndex(String indexName) {
        CreateIndexRequest index = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse response = client.indices().create(index, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 插入文档
     */
    public void insertDoc(User user,String indexName) {
        IndexRequest request = new IndexRequest(indexName);
        request.id(user.getId());
        //将对象转为JSON格式放入请求中
        request.source(JSON.toJSONString(user), XContentType.JSON);
        try {
            //由客户端对象执行请求
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            //System.out.println("请求返回状态：" + response.status());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量添加
     */
    public void addUsers(List<User> users,String indexName) {
        BulkRequest request = new BulkRequest(indexName);
        //提取出所有要添加用户的id,根据id将对象转为JSON格式放入请求中
        for (User user : users) {
            request.add(new IndexRequest().id(user.getId()).source(JSON.toJSONString(user),XContentType.JSON));
        }
        try {
            client.bulk(request,RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id查询数据
     */
    public User findById(String id,String indexName){
        GetRequest request = new GetRequest(indexName);
        request.id(id);
        String json=null;
        try {
            GetResponse fields = client.get(request, RequestOptions.DEFAULT);
            json = fields.getSourceAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.parseObject(json,User.class) ;
    }

    /**
     * 查询文档
     */
    public List<User> searchDoc(String indexName) {
        SearchRequest request = new SearchRequest(indexName);
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<User> list = new ArrayList<>();
        if(response!=null){
            //获取SearchHit数组
            SearchHit[] searchHits = response.getHits().getHits();
            for (SearchHit searchHit : searchHits) {
                //把SearchHit对象转换成字符串
                String source = searchHit.getSourceAsString();
                list.add(JSON.parseObject(source, User.class));
            }
        }
        return list;
    }

    /**
     * 分页查询
     */
    public List<User> pageQuery(String indexName,Integer page,Integer size){
        //构建SearchRequest请求对象，指定索引库
        SearchRequest request =new SearchRequest(indexName);
        //构建SearchSourceBuilder查询对象,选择查询全部
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        //分页
        sourceBuilder.from(page);
        sourceBuilder.size(size);
        request.source(sourceBuilder);
        //获取查询结果
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<User> list = new ArrayList<>();
        if(response!=null) {
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                //把SearchHit对象转换成字符串
                String source = hit.getSourceAsString();
                list.add(JSON.parseObject(source, User.class));
            }
        }
        return list;
    }

    /**
     * 根据id删除用户
     */
    public void deleteById(String id,String indexName) {
        DeleteRequest request = new DeleteRequest(indexName);
        request.id(id);
        try {
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     */
    public void deleteByIds(List<String> ids, String indexName) {
        BulkRequest request = new BulkRequest(indexName);
        //添加所有集合中的id
        for (String id : ids){
            request.add(new DeleteRequest().id(id));
        }
        try {
            client.bulk(request,RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新用户
     */
    public void updateById(User user, String indexName) {
        UpdateRequest request = new UpdateRequest(indexName,user.getId());
        request.doc(JSON.toJSONString(user),XContentType.JSON);
        try {
            client.update(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
